<?php

namespace Common\Model\Cache;

abstract class Base
{
    protected $cacheName;

    public function __construct()
    {
        if (!$this->cacheName) {
            $this->setDefaultCacheName();
        }
    }

    abstract public function refresh();

    public function get()
    {
        $cache = F($this->cacheName);
        if ($cache) {
            return $cache;
        } else {
            return $this->refresh();
        }
    }

    protected function save($data)
    {
        F($this->cacheName, $data);
    }

    /**
     * 数据写入配置文件
     * @param string $path
     * @param array  $data
     * @return bool
     */
    protected function saveConfig($path, $data)
    {
        $content = "<?php \nreturn ";
        $content .= var_export($data, true) . ";\r\n";
        $content .= "?>";
        if (file_put_contents($path, $content, LOCK_EX)) {
            return true;
        }
        return false;
    }

    private function setDefaultCacheName()
    {
        $name            = get_class($this);
        $cacheName       = substr($name, strrpos($name, '\\') + 1);
        $this->cacheName = parse_name($cacheName);
    }
}